<script setup lang="ts">
import { onMounted, onUnmounted, computed, ref } from "vue";
import { useCustomerServiceStore } from "@/store/modules/customerService";
import MessageStream from "@/components/CustomerService/MessageStream.vue";
import MessageInput from "@/components/CustomerService/MessageInput.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ChatDotRound, ArrowLeft, Phone, Message, Plus, User, Delete } from "@element-plus/icons-vue";
import type { ChatRoom } from "@/api/customer-service";

defineOptions({
  name: "CustomerServiceInbox"
});

const store = useCustomerServiceStore();

// 左侧面板状态
const searchQuery = ref("");
const sortMode = ref("newest"); // newest, oldest

// 右侧面板状态
const rightPanelTab = ref<"customer" | "users">("users"); // customer: 客户信息, users: 用户列表
const userSearchKeyword = ref("");
const onlineFilterMode = ref<"all" | "online" | "offline">("all");

// 移动端状态
const isMobile = ref(false);

// 在挂载时初始化
onMounted(() => {
  // 检测屏幕尺寸
  checkMobile();
  window.addEventListener("resize", checkMobile);
});

// 在卸载时清理
onUnmounted(() => {
  window.removeEventListener("resize", checkMobile);
});

const checkMobile = () => {
  isMobile.value = window.innerWidth < 768;
};

// ==================== 会话列表相关 ====================

// 过滤和排序后的会话列表
const filteredRooms = computed(() => {
  let rooms = [...store.myRooms, ...store.newRooms];
  // console.log("xxxxxxx:", rooms);
  // 搜索过滤
  if (searchQuery.value.trim()) {
    const keyword = searchQuery.value.toLowerCase();
    rooms = rooms.filter(room => {
      const name = getUserDisplayName(room).toLowerCase();
      const lastMessage = room.last_message?.content?.toLowerCase() || "";
      return name.includes(keyword) || lastMessage.includes(keyword);
    });
  }

  // 排序
  if (sortMode.value === "oldest") {
    rooms.sort((a, b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());
  } else {
    // newest
    rooms.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
  }

  return rooms;
});

// 处理房间选择
const handleRoomSelect = async (roomId: number) => {
  await store.selectRoom(roomId);
  // 切换到客户信息面板
  rightPanelTab.value = "customer";
};

const handleCommand = (command: string) => {
  if (command === "delete") {
    // store.hideRoom(store.currentRoomId);
    ElMessage.info("删除会话功能待实现");
  }
};
// 删除会话（隐藏）
const handleDeleteRoom = async (room: ChatRoom, event: Event) => {
  event.stopPropagation();

  try {
    await ElMessageBox.confirm(`确定要删除与 ${getUserDisplayName(room)} 的会话吗？`, "删除会话", {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning"
    });
    // 调用隐藏删除会话 API
    await store.hideRoom(room.id);
    ElMessage.success("会话已删除");

    // 如果删除的是当前会话，清除选择
    if (store.currentRoomId === room.id) {
      store.clearSelection();
    }
  } catch (error) {
    // 用户取消或删除失败（已在 store 中处理错误提示）
    if (error !== "cancel") {
      console.error("删除房间错误:", error);
    }
  }
};

// 处理右键菜单命令
const handleRoomContextMenu = async (command: string, room: ChatRoom) => {
  switch (command) {
    case "delete":
      // 复用删除逻辑，创建模拟事件
      await handleDeleteRoom(room, new Event("click"));
      break;
    case "markRead":
      // 标记为已读
      try {
        await store.markRoomAsRead(room.id);
        ElMessage.success("已标记为已读");
      } catch (error) {
        console.error("标记已读失败:", error);
        ElMessage.error("标记已读失败");
      }
      break;
    case "mute":
      // 静音通知功能（待实现）
      ElMessage.info("静音通知功能待实现");
      break;
  }
};

// 获取用户完整信息
const getUserInfo = (room: any) => {
  if (!room) {
    return {
      name: "未知用户",
      avatar: null,
      is_online: false,
      online_status: "离线"
    };
  }
  if (room?.type === "group") {
    return {
      name: room.name || "群聊",
      avatar: null,
      is_online: false,
      online_status: "离线",
      type: "group"
    };
  }
  const otherUser = room?.participants?.find((p: any) => p.type === "NormalUser");
  if (otherUser) {
    // 主要以 is_online (布尔值) 为准，online_status (字符串) 用于显示
    const isOnline = otherUser.is_online ?? false;
    return {
      ...otherUser,
      is_online: isOnline,
      online_status: otherUser.online_status || (isOnline ? "在线" : "离线")
    };
  }
  return {
    name: "用户",
    avatar: null,
    is_online: false,
    online_status: "离线"
  };
};

// 获取用户显示名称（兼容旧代码）
const getUserDisplayName = (room: any) => {
  return getUserInfo(room).name || "用户";
};

// 格式化时间
const formatTime = (dateStr?: string) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (minutes < 1) return "刚刚";
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  return date.toLocaleDateString();
};

// ==================== 聊天相关 ====================

// Handle send message
const handleSendMessage = (content: string, type: string) => {
  if (store.currentRoomId) {
    store.sendMessage(store.currentRoomId, content, type);
  }
};

// Handle typing status
const handleTyping = (isTyping: boolean) => {
  if (store.currentRoomId) {
    store.sendTypingStatus(store.currentRoomId, isTyping);
  }
};

// 计算输入指示文本
const typingIndicatorText = computed(() => {
  if (!store.currentRoomId) return "";
  const typingUserIds = store.typingUsers[store.currentRoomId] || [];
  if (typingUserIds.length === 0) return "";
  return "对方正在输入...";
});

// ==================== 客户信息相关 ====================

// 当前客户信息
const currentCustomer = computed(() => {
  if (!store.currentRoom) return null;
  return store.currentRoom.participants?.find((p: any) => p.type === "NormalUser");
});

// 客户标签（示例数据）
const customerTags = ref(["VIP客户", "活跃用户"]);

// 添加标签
const handleAddTag = async () => {
  try {
    const { value: tagName } = await ElMessageBox.prompt("请输入标签名称", "添加标签", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /\S+/,
      inputErrorMessage: "标签名称不能为空"
    });

    if (tagName && !customerTags.value.includes(tagName)) {
      customerTags.value.push(tagName);
      ElMessage.success("标签已添加");
    }
  } catch (error) {
    // 用户取消
  }
};

// 移除标签
const handleRemoveTag = (tag: string) => {
  customerTags.value = customerTags.value.filter(t => t !== tag);
  ElMessage.success("标签已移除");
};

// ==================== 用户列表相关 ====================

// 过滤后的用户列表
const filteredUsers = computed(() => {
  let users = store.clientUsers;

  // 在线状态过滤
  if (onlineFilterMode.value === "online") {
    users = users.filter(u => u.online_status);
  } else if (onlineFilterMode.value === "offline") {
    users = users.filter(u => !u.online_status);
  }

  // 搜索过滤
  if (userSearchKeyword.value.trim()) {
    const keyword = userSearchKeyword.value.toLowerCase();
    users = users.filter(
      u =>
        u.username?.toLowerCase().includes(keyword) ||
        u.phone?.toLowerCase().includes(keyword) ||
        u.email?.toLowerCase().includes(keyword)
    );
  }

  return users;
});

// 在线用户数量
const onlineUsersCount = computed(() => {
  return store.clientUsers.filter(u => u.online_status).length;
});

// 搜索用户
const handleUserSearch = () => {
  store.searchClientUsers(userSearchKeyword.value);
};

// 创建与用户的聊天
const handleStartChatWithUser = async (userId: number) => {
  await store.startChatWithUser(userId);
  rightPanelTab.value = "customer";
};

// 格式化用户时间
const formatUserTime = (dateStr?: string) => {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / 86400000);

  if (days === 0) {
    const hours = Math.floor(diff / 3600000);
    if (hours === 0) {
      const minutes = Math.floor(diff / 60000);
      return minutes === 0 ? "刚刚" : `${minutes}分钟前`;
    }
    return `${hours}小时前`;
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// ==================== 移动端适配 ====================

// 返回列表
const handleBackToList = () => {
  store.clearSelection();
};
</script>

<template>
  <div class="flex h-[85vh] bg-gray-50 overflow-hidden">
    <!-- 左侧：会话列表面板 -->
    <div
      class="w-80 bg-white border-r border-gray-200 flex flex-col"
      :class="{ 'hidden md:flex': store.currentRoomId && isMobile }"
    >
      <!-- 头部 -->
      <div class="px-4 py-4 border-b border-gray-200 flex-shrink-0">
        <h2 class="text-xl font-semibold text-gray-800 mb-3">会话列表</h2>

        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索会话..."
          prefix-icon="Search"
          clearable
          size="default"
          class="mb-3"
        />

        <!-- 排序选项 -->
        <div class="flex gap-2">
          <el-button
            :type="sortMode === 'newest' ? 'primary' : ''"
            size="small"
            plain
            @click="sortMode = 'newest'"
          >
            最新
          </el-button>
          <el-button
            :type="sortMode === 'oldest' ? 'primary' : ''"
            size="small"
            plain
            @click="sortMode = 'oldest'"
          >
            最旧
          </el-button>
        </div>
      </div>

      <!-- 会话列表 -->
      <!--#region -->
      <div class="flex-1 overflow-y-auto">
        <!-- 新请求会话 -->
        <div v-if="store.newRooms.length > 0" class="px-4 py-2 bg-blue-50 border-b border-blue-100">
          <span class="text-xs font-semibold text-blue-600">新请求 ({{ store.newRooms.length }})</span>
        </div>

        <div v-for="room in filteredRooms" :key="room.id">
          <div
            class="px-4 py-3 border-b border-gray-100 cursor-pointer hover:bg-gray-50 transition-colors relative group"
            :class="{
              'bg-blue-50 border-l-4 border-l-blue-500': room.id === store.currentRoomId
            }"
            @click="handleRoomSelect(room.id)"
            @contextmenu.prevent
          >
            <div class="flex items-start gap-3">
              <!-- 头像 -->
              <div class="relative flex-shrink-0">
                <el-avatar :size="48" :src="getUserInfo(room).avatar || ''">
                  {{ getUserDisplayName(room).charAt(0) }}
                </el-avatar>
                <!-- 在线状态指示 -->
                <span
                  v-if="getUserInfo(room).is_online"
                  class="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-white rounded-full"
                />
              </div>

              <!-- 会话信息 -->
              <div class="flex-1 min-w-0">
                <div class="flex items-center justify-between mb-1">
                  <span class="font-medium text-gray-900 truncate">
                    {{ getUserDisplayName(room) }}
                  </span>
                  <span class="text-xs text-gray-500 ml-2 flex-shrink-0">
                    {{ formatTime(room.updated_at) }}
                  </span>
                </div>

                <div class="flex items-center justify-between">
                  <p class="text-sm text-gray-600 truncate">
                    {{ room.last_message?.content || "暂无消息" }}
                  </p>
                  <!-- 未读标记 -->
                  <el-badge
                    v-if="room.unread_count && room.unread_count > 0"
                    :value="room.unread_count"
                    :max="99"
                    class="ml-2 flex-shrink-0"
                  />
                </div>

                <!-- 新会话标记 -->
                <el-tag v-if="room.status === 'new'" type="warning" size="small" class="mt-1">
                  待接入
                </el-tag>
              </div>
              <!-- 删除按钮 -->
              <el-button
                text
                circle
                size="small"
                class="opacity-0 group-hover:opacity-100 transition-opacity absolute top-9 right-3"
                @click="handleDeleteRoom(room, $event)"
              >
                <el-icon color="#ff0000" size="16px"><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
        <!-- 空状态 -->
        <div
          v-if="filteredRooms.length === 0"
          class="flex flex-col items-center justify-center h-64 text-gray-400"
        >
          <el-icon :size="48" class="mb-2"><ChatDotRound /></el-icon>
          <p>暂无会话</p>
        </div>
      </div>
      <!--#endregion -->
    </div>

    <!-- 中间：聊天区域 -->
    <div
      class="flex-1 flex flex-col bg-white"
      :class="{ 'hidden md:flex': !store.currentRoomId && isMobile }"
    >
      <template v-if="store.currentRoomId && store.currentRoom">
        <!-- 聊天头部 -->
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between flex-shrink-0">
          <div class="flex items-center gap-3">
            <!-- 返回按钮（移动端） -->
            <el-button v-if="isMobile" text circle @click="handleBackToList">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>

            <el-avatar :size="40" :src="getUserInfo(store.currentRoom).avatar || ''">
              {{ getUserDisplayName(store.currentRoom).charAt(0) }}
            </el-avatar>

            <div>
              <h3 class="font-semibold text-gray-900">
                {{ getUserDisplayName(store.currentRoom) }}
              </h3>
              <p class="text-sm text-gray-500">
                {{ typingIndicatorText || getUserInfo(store.currentRoom).online_status }}
              </p>
            </div>
          </div>

          <div class="flex items-center gap-2">
            <!-- 可以在这里添加其他操作按钮 -->
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="flex-1 overflow-hidden">
          <MessageStream :messages="store.currentMessages" />
        </div>

        <!-- 输入区域 -->
        <div class="border-t border-gray-200 flex-shrink-0">
          <MessageInput @send="handleSendMessage" @typing="handleTyping" />
        </div>
      </template>

      <!-- 空状态 -->
      <div v-else class="flex-1 flex items-center justify-center text-gray-400">
        <div class="text-center">
          <el-icon :size="64" class="mb-4"><ChatDotRound /></el-icon>
          <p class="text-lg">选择一个会话开始聊天</p>
          <p class="text-sm mt-2">或从右侧用户列表发起新会话</p>
        </div>
      </div>
    </div>

    <!-- 右侧：客户信息/用户列表面板 -->
    <div class="w-80 bg-white border-l border-gray-200 flex flex-col" :class="{ 'hidden lg:flex': isMobile }">
      <!-- Tab 切换 -->
      <div class="px-4 py-3 border-b border-gray-200 flex gap-2 flex-shrink-0">
        <el-button
          :type="rightPanelTab === 'customer' ? 'primary' : ''"
          plain
          class="flex-1"
          @click="rightPanelTab = 'customer'"
        >
          客户信息
        </el-button>
        <el-button
          :type="rightPanelTab === 'users' ? 'primary' : ''"
          plain
          class="flex-1"
          @click="rightPanelTab = 'users'"
        >
          用户列表
        </el-button>
      </div>

      <!-- 客户信息面板 -->
      <div v-if="rightPanelTab === 'customer'" class="flex-1 overflow-y-auto p-4">
        <template v-if="currentCustomer">
          <!-- 客户基本信息 -->
          <div class="text-center mb-6">
            <el-avatar :size="80" :src="currentCustomer.avatar || ''">
              {{ currentCustomer.name.charAt(0) }}
            </el-avatar>
            <h3 class="text-lg font-semibold mt-3 text-gray-900">
              {{ currentCustomer.name }}
            </h3>
            <p class="text-sm text-gray-500">ID: {{ currentCustomer.id }}</p>
            <el-tag :type="currentCustomer.online_status ? 'success' : 'info'" size="small" class="mt-2">
              {{ currentCustomer.online_status ? "在线" : "离线" }}
            </el-tag>
          </div>

          <!-- 联系方式 -->
          <div class="mb-6">
            <h4 class="text-sm font-semibold text-gray-700 mb-3">联系方式</h4>
            <div class="space-y-2">
              <div v-if="currentCustomer.phone" class="flex items-center text-sm text-gray-600">
                <el-icon class="mr-2"><Phone /></el-icon>
                <span>{{ currentCustomer.phone }}</span>
              </div>
              <div v-if="currentCustomer.email" class="flex items-center text-sm text-gray-600">
                <el-icon class="mr-2"><Message /></el-icon>
                <span>{{ currentCustomer.email }}</span>
              </div>
            </div>
          </div>

          <!-- 客户标签 -->
          <div class="mb-6">
            <div class="flex items-center justify-between mb-3">
              <h4 class="text-sm font-semibold text-gray-700">客户标签</h4>
              <el-button text size="small" @click="handleAddTag">
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
            <div class="flex flex-wrap gap-2">
              <el-tag v-for="tag in customerTags" :key="tag" closable @close="handleRemoveTag(tag)">
                {{ tag }}
              </el-tag>
              <el-tag v-if="customerTags.length === 0" type="info">暂无标签</el-tag>
            </div>
          </div>

          <!-- 客户统计 -->
          <div class="mb-6">
            <h4 class="text-sm font-semibold text-gray-700 mb-3">统计信息</h4>
            <div class="space-y-2 text-sm">
              <div class="flex justify-between text-gray-600">
                <span>注册时间</span>
                <span>{{ formatUserTime(currentCustomer.registered_at) }}</span>
              </div>
              <div class="flex justify-between text-gray-600">
                <span>最后活跃</span>
                <span>{{ formatUserTime(currentCustomer.last_active_at) }}</span>
              </div>
            </div>
          </div>
        </template>

        <!-- 无客户信息 -->
        <div v-else class="flex flex-col items-center justify-center h-64 text-gray-400">
          <el-icon :size="48" class="mb-2"><User /></el-icon>
          <p>请选择会话查看客户信息</p>
        </div>
      </div>

      <!-- 用户列表面板 -->
      <div v-if="rightPanelTab === 'users'" class="flex flex-col overflow-hidden">
        <!-- 搜索和筛选 -->
        <div class="px-4 py-3 border-b border-gray-200 flex-shrink-0">
          <el-input
            v-model="userSearchKeyword"
            placeholder="搜索用户..."
            prefix-icon="Search"
            clearable
            size="default"
            class="mb-3"
            @input="handleUserSearch"
          />

          <!-- 在线状态筛选 -->
          <div class="flex gap-2">
            <el-button
              :type="onlineFilterMode === 'all' ? 'primary' : ''"
              size="small"
              plain
              @click="onlineFilterMode = 'all'"
            >
              全部 ({{ store.clientUsers.length }})
            </el-button>
            <el-button
              :type="onlineFilterMode === 'online' ? 'primary' : ''"
              size="small"
              plain
              @click="onlineFilterMode = 'online'"
            >
              在线 ({{ onlineUsersCount }})
            </el-button>
            <el-button
              :type="onlineFilterMode === 'offline' ? 'primary' : ''"
              size="small"
              plain
              @click="onlineFilterMode = 'offline'"
            >
              离线
            </el-button>
          </div>
        </div>

        <!-- 用户列表 -->
        <div v-loading="store.clientUsersLoading" class="flex-1 overflow-y-auto">
          <div
            v-for="user in filteredUsers"
            :key="user.id"
            class="px-4 py-3 border-b border-gray-100 cursor-pointer hover:bg-gray-50 transition-colors"
            @click="handleStartChatWithUser(user.id)"
          >
            <div class="flex items-center gap-3">
              <!-- 头像 -->
              <div class="relative flex-shrink-0">
                <el-avatar :size="40" :src="user.avatar || ''">
                  {{ user.nickname.charAt(0) }}
                </el-avatar>
                <!-- 在线状态指示 -->
                <span
                  v-if="false"
                  :class="[
                    'absolute bottom-0 right-0 w-3 h-3 border-2 border-white rounded-full',
                    user.online_status ? 'bg-green-500' : 'bg-gray-400'
                  ]"
                />
              </div>

              <!-- 用户信息 -->
              <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2">
                  <span class="font-medium text-gray-900 truncate">{{ user.nickname }}</span>
                  <el-tag v-if="user.online_status" type="success" size="small">在线</el-tag>
                </div>
                <p class="text-xs text-gray-500 truncate mt-1">
                  {{ user.phone || user.email || `ID: ${user.id}` }}
                </p>
              </div>

              <!-- 发起聊天图标 -->
              <el-icon class="text-gray-400"><ChatDotRound /></el-icon>
            </div>
          </div>

          <!-- 空状态 -->
          <div
            v-if="filteredUsers.length === 0"
            class="flex flex-col items-center justify-center h-64 text-gray-400"
          >
            <el-icon :size="48" class="mb-2"><User /></el-icon>
            <p>暂无用户</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// 响应式调整
@media (width <= 768px) {
  .mobile-hidden {
    display: none;
  }
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

// Element Plus 样式覆盖
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;

  &:hover {
    box-shadow: 0 0 0 1px #c0c4cc inset;
  }

  &.is-focus {
    box-shadow: 0 0 0 1px var(--el-color-primary) inset;
  }
} // 自定义滚动条样式
</style>
